package comm;
import java.io.IOException;
import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.MulticastSocket;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Observable;

public class UdpReceiver extends Observable implements Runnable{

	private MulticastSocket socket;
	private InetAddress group;
	private DatagramPacket packet; 

	UdpReceiver (NetworkInterface ni, int port, String groupName) throws IOException{

		//setting up socket
		socket =  new MulticastSocket(port);
		group = InetAddress.getByName(groupName);

		socket.setNetworkInterface(ni);
		socket.joinGroup(group);
		packet = new DatagramPacket(new byte[ni.getMTU()], ni.getMTU());
	}

	@Override
	public void run() {
		//try to receive a packet on the network interface

		while (!socket.isClosed()){
			try {
				socket.receive(packet);//waiting to receive packet

				//setChanged and notify any observers with the packet data
				this.setChanged();
				this.notifyObservers(packet);
			} catch (SocketException e) {
				//most likely a caused by the close method below
			} catch (IOException e) {
				System.err.println("IO Exception receiving datagram packet in receiver");
			} 
		}
	}

	public void close(){
		socket.close();
	}

}
